package uia.alumni.profile;

import java.io.PrintWriter;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.http.HttpServletRequest;
import uia.alumni.data.User;
import uia.alumni.web.Page;

import static uia.alumni.web.Constants.*;
import static uia.alumni.profile.Constants.*;
import static uia.alumni.form.FieldType.*;

/**
 * Make a form for registering a new user.
 * @author Even Åby Larsen (even.larsen@uia.no)
 * @author Simon Zimmermann
 */
public class RegisterProfile extends Page {

    /** SERVLET_NAME is used for consistency checking of web.xml */
    public static final String SERVLET_NAME = "profile.register";
    @PersistenceUnit(name = PERSISTENCE_UNIT)
    private EntityManagerFactory emf;

    public RegisterProfile() {
        super(null);
    }

    public void writeBody(PrintWriter out, HttpServletRequest request) {
        EntityManager em = emf.createEntityManager();
        User user = getLoggedInUser(em, request);

        out.println("<h1>Register</h1>");
        if (user == null) {
            out.println("<p>Please enter your email address, name and a password of your choice.</p>");
            // If form has been submitted and had errors. This will show them.
            writeFormErrors(out, request);

            out.println("<ul>");
            out.println(tagForm(CreateProfile.SERVLET_NAME));
            // --------------- INPUT: ( name    | type | label      | value )
            out.println(tagLi(tagField(FULLNAME, TEXT, "Full Name:")));
            out.println(tagLi(tagField(MAIL, EMAIL, "Email Address:")));
            out.println(tagLi(tagField(PASSWORD, PW, "Password:")));
            out.println(tagLi(tagField(PASSWORD, PW, "Repeat Password:")+
                    "<input type=\"hidden\" value=" + SERVLET_NAME + " name=\"from\">"));
            out.println(tagLi(tagField(SUBMIT.toString(), SUBMIT, "Register")));
            out.println("</form>");
            out.println("<ul>");
        } else {
            out.println("You are registered as " + user.getFullName() + " (" + user.getEmail() + ")");
        }
    }
    public final static long serialVersionUID = 1;
}
